<?php
/**
 * Created by PhpStorm.
 * User: Happy
 * Date: 2016/5/18 0018
 * Time: 14:12
 */
//引入发送请求等函数的库
//按钮类型常量
class Button_Type
{

    const  click = 'click';//点击事件
    const  view = 'view';//跳转URL
    const  scancode_push = 'scancode_push';//扫码事件
    const  scancode_waitmsg = 'scancode_waitmsg';//扫码推事件且弹出“消息接收中”提示框
    const  pic_sysphoto = "pic_sysphoto";//系统拍照发图
    const  pic_photo_or_album = 'pic_photo_or_album';//拍照或者相册发图
    const pic_weixin = 'pic_weixin';//微信相册发图器
    const location_select = 'location_select';//地理位置选择器
    //const media_id='media_id';//下发消息（除文本消息）用户点击media_id类型按钮后，微信服务器会将开发者填写的永久素材id对应的素材下发给用户，永久素材类型可以是图片、音频、视频、图文消息。请注意：永久素材id必须是在“素材管理/新增永久素材”接口上传后获得的合法id
    // const view_limited='view_limited';//跳转图文消息 url
}

class wechatPlugin extends  Plugin{

      private  $util=null;

    function __construct($pluginfile='')
    {
        parent::__construct($pluginfile);
        $this->util=plugin($this->config['util_plugin']);
    }

    //根据code参数获取open_id，前提是用户已经关注微信号，经过确认（未关注的情况）或者已经关注直接跳转到业务逻辑页面
    //参考url：http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
    public  function  get_openid(){

        $util=$this->util;
        $config=$this->config;

        if(!$_GET['code']){

            $redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

            if(stristr($redirect,'localhost')){
                exit('获取openid的url不能是localhost和有端口;必须设置域名或者更改本地host');
            }

           // $redirect='http://ju3n.com/mobile/index.php';
            $appid=$config['app_id'];
            //测试获取用户的openid
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect.'&response_type=code&scope=snsapi_base&state=123#wechat_redirect';

            $util->redirect($url);

        }else{

            if(isset($_GET['code'])&&$_GET['code']){
                $code=$_GET['code'];
                //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
                $setting=array(
                    'appid'=>$config['app_id'],
                    'secret'=>$config['app_secret'],
                    'code'=>$code,
                    'grant_type'=>'authorization_code'
                );

                //  write($setting);
                $data=$util->httpGet($config['OPENID_TOKEN_URL'],$setting);
                //write($data);
                $data=json_decode($data,true)  ;
                if(isset($data['openid'])){
                    return  $data['openid'];//返回openid
                }
                else{
                    return false;
                }
            }
        }
        return false;
    }

    //获取token
    public function  get_token()
    {
        $util=$this->util;
        $config=$this->config;
        $cache_path=$config['plugin_path'].'/cache';
        $cache_key='tocken';
        $token =$util->get_cache($cache_key,$cache_path,$config['access_tocken_timeout']);

        if ($token) {
            //echo 'from cache';
            return $token;
        } else {
            //echo 'from url';
            $param = array(
                'grant_type' => 'client_credential',
                'appid' =>$config['app_id'],
                'secret' => $config['app_secret']
            );
            $result = $util->httpGet($config['TOKEN_URL'], $param);

            $obj = json_decode($result);
            if ($obj->access_token) {
                //存入缓存文件中，设置过期时间和比较
               $util->set_cache($cache_key, $obj->access_token, $cache_path); //两个小时过期，暂时设置成7000秒
                return $obj->access_token;
            } else { //出错
                return false;
                // exit('get access token  error，error info is' . $obj->errmsg);
            }
        }
    }

    // 获取jsapi_ticket
    public  function  get_jsapi_ticket(){
        $util=$this->util;
        $config=$this->config;
        $cache_path=$config['plugin_path'].'/cache';

        //?access_token=ACCESS_TOKEN&type=jsapi
        $ticket_cache_key='jsapi_ticket';
        $ticket = $util->get_cache($ticket_cache_key,$cache_path,$config['access_tocken_timeout']);
        if ($ticket) {
            //echo 'from cache';
            return $ticket;
        } else {
            //echo 'from url';
            $param = array(
                'access_token' => $this->get_token(),
                'type' => 'jsapi'
            );
            $result = $util->httpGet($config['JS_API_TICKET_URL'], $param);
            $obj = json_decode($result);
            if ($obj->ticket) {
                //存入缓存文件中，设置过期时间和比较
                $util-> set_cache($ticket_cache_key, $obj->ticket,$cache_path); //两个小时过期，暂时设置成7000秒
                return $obj->ticket;
            } else { //出错
                return false;
                // exit('get access token  error，error info is' . $obj->errmsg);
            }
        }
    }

    //获取配置的数组
    public function getSignPackage() {

        $util=$this->util;
        $config=$this->config;

        $jsapiTicket = $this->get_jsapi_ticket();

        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $util->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $config['app_id'],
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }


    //获取配置的json字符串
    public  function get_config_json($isArray=false){
       // $util=$this->util;
        $config=$this->config;

        $sign_package=$this->getSignPackage();
        $config=array(
            'debug'=> false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            'appId'=>$config['app_id'], // 必填，公众号的唯一标识
            'timestamp'=>$sign_package['timestamp'], // 必填，生成签名的时间戳
            "nonceStr"  =>$sign_package['nonceStr'], // 必填，生成签名的随机串
            'signature'=>$sign_package['signature'],// 必填，签名，见附录1
            'jsApiList'=>$config['jsApiList']// 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        );
        if($isArray){
            return $config;
        }
        else{
            return json_encode($config);
        }

    }

    //设置菜单
    public function  set_menu($menu = array())
    {
        $util=$this->util;
        $config=$this->config;
        //如果网页需要用户openid,可以先跳入此页面授权再自动跳到需要的页面
        //http://121.42.159.58/mwerichat/wechat/control.php?act=scanner
        //'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0d007463ea784623&redirect_uri=http://121.42.159.58/mweichat/wechat/control.php?act=scanner&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
        if (!$menu) {
            $menu = $config['menu'];
        }
        $url=$config['MENU_URL'].'?access_token='.$this->get_token();
        $body=$util-> json_encode_no_zh($menu);
        $result=  $util->post($url,$body);
        $arr=json_decode($result,true);//转化为数组

        if($arr['errmsg']=='ok'){
            return true; //创建成功
        }
        else{
            return false;//创建失败
        }


    }

   //设置信息

    //发送文本信息
    public  function  send_msg($openid){

    }
    //发送图文信息
    public   function  send_news($setting){


    }
//-------------------用户函数------------
    //获取用户列表
    public  function  get_user_list(){
       // $util=$this->util;
        $config=$this->config;
        //  ?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID
        $token=$this->get_token();
        $url=$config['USER_LIST_URL'].'?ACCESS_TOKEN='.$token;
        $json=file_get_contents($url);
        return $json;
    }


    //保存基本信息oefTts-4vEH26RsOpuZ6Rx9IRWqM
    public  function  get_user_info($open_id){//nickname
      // $util=$this->util;
        $config=$this->config;
        //$open_id='oefTts-4vEH26RsOpuZ6Rx9IRWqM';
        $url= $config['USER_INFO_URL'].'?'.'access_token='.$this->get_token().'&openid='.$open_id.'&lang=zh_CN';
        $content=file_get_contents($url);
        return $content;
    }
    //没有关注的情况下获取用户的基本信息，通过用户授权获取信息
    public  function  getUserInfoByAuth(){

        $util=$this->util;
        $config=$this->config;

        if(!$_GET['code']){

            $redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

            if(stristr($redirect,'localhost')){
                exit('获取openid的url不能是localhost和有端口;必须设置域名或者更改本地host');
            }

            // $redirect='http://ju3n.com/mobile/index.php';
            $appid=$config['app_id'];
            //测试获取用户的openid
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect.'&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect';

            $util->redirect($url);

        }else{

            if(isset($_GET['code'])&&$_GET['code']){
                $code=$_GET['code'];
                //https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
                $setting=array(
                    'appid'=>$config['app_id'],
                    'secret'=>$config['app_secret'],
                    'code'=>$code,
                    'grant_type'=>'authorization_code'
                );

                //  write($setting);
                $data=$util->httpGet($config['OPENID_TOKEN_URL'],$setting);
                //write($data);


                $data=json_decode($data,true);

                 if(isset($data['access_token'])){
                      $token=$data['access_token'];
                     $openid=$data['openid'];
                     $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$token.'&openid='.$openid.'&lang=zh_CN';
                     return file_get_contents($url);
                     /**
                     返回json格式：
                      * 正确时返回的JSON数据包如下：
                     {    "openid":" OPENID",
                     " nickname": NICKNAME,
                     "sex":"1",
                     "province":"PROVINCE"
                     "city":"CITY",
                     "country":"COUNTRY",
                     "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ
                     4eMsv84eavHiaiceqxibJxCfHe/46",
                     "privilege":[ "PRIVILEGE1" "PRIVILEGE2"     ],
                     "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
                     }

                      */
                 }
                else{
                    return false;//请求失败，用户没有同意
                }



            }
        }
        return false;
    }



    //获取素材列表
    public  function  get_batch_material($setting=array()){
        $util=$this->util;
        $config=$this->config;
        /*example setting
         *array(
    'type'=>'image',
    'offset'=>0,
    'count'=>20
    )
         *
         * */
        $token=$this->get_token();
        //var_dump($setting);die;
        $url=$config['BATCH_MATERIAL_URL'].'?ACCESS_TOKEN='.$token;
        $json=$util->post($url,json_encode($setting));
        return $json;
    }


}